<?php

namespace App\Http\Controllers;

use App\Http\Resources\LoginLogResource;
use App\Http\Traits\CheckPermission;
use App\Models\LoginLog;
use App\Models\Permission;
use Illuminate\Http\Request;

class LoginLogController extends Controller
{
    use CheckPermission;

    protected $resource = 'login_logs';

    public function __construct()
    {
        $this->middleware('auth.api');
    }

    /**
     * 获取登录日志列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $query = LoginLog::with('user');

        if ($request->filled('username')) {
            $query->where('username', 'like', '%' . $request->username . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('start_time')) {
            $query->where('login_at', '>=', $request->start_time);
        }

        if ($request->filled('end_time')) {
            $query->where('login_at', '<=', $request->end_time);
        }

        $logs = $query->orderBy('login_at', 'desc')
            ->paginate($this->getPageSize($request));

        // 使用Resource格式化分页数据，包括时间字段
        // 将Resource对象转换为数组，确保时间格式正确
        $logs->setCollection(
            $logs->getCollection()->map(function ($log) {
                return (new LoginLogResource($log))->resolve(request());
            })
        );

        return $this->success($logs, '获取成功');
    }

    /**
     * 获取登录日志详情
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $log = LoginLog::with('user')->findOrFail($id);
        return $this->success(new LoginLogResource($log), '获取成功');
    }

    /**
     * 删除登录日志
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $log = LoginLog::findOrFail($id);
        $log->delete();
        return $this->success(null, '删除成功');
    }

    /**
     * 清空登录日志
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clear()
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        LoginLog::truncate();
        return $this->success(null, '清空成功');
    }
}

